package com.xiaoyu.lanling.feature.invite.dialog

import `in`.srain.cube.util.CheckUtil
import `in`.srain.cube.util.UTUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.google.android.flexbox.FlexboxLayout
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.ClipboardUtils
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseBottomSheetDialogFragment
import com.xiaoyu.lanling.event.invite.InviteShareInfoEvent
import com.xiaoyu.lanling.feature.invite.data.InviteData
import com.xiaoyu.lanling.share.ShareController
import com.xiaoyu.lanling.share.ShareHelper
import com.xiaoyu.lanling.util.AppUtil
import kotlinx.android.synthetic.main.invite_share_dialog.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class InviteShareDialog : BaseBottomSheetDialogFragment() {
    private val requestTag = Any()

    companion object {
        private const val TAG = "InviteShareDialog"

        fun show(fragmentManager: FragmentManager) {
            val fragment: BaseBottomSheetDialogFragment = (fragmentManager.findFragmentByTag(TAG) as? BaseBottomSheetDialogFragment)
                    ?: InviteShareDialog()
            if (fragment.isAdded) return
            fragment.show(fragmentManager, TAG)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.invite_share_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initView()
        initBind()
        initEvent()
        initData()
    }

    override fun onResumeSafelyAfterAppFinishInit(isFirstTimeResume: Boolean) {
        super.onResumeSafelyAfterAppFinishInit(isFirstTimeResume)
        val parent = view?.parent as? ViewGroup
        parent?.setBackgroundResource(R.color.colorTransparent)
    }

    private fun initData() {
        InviteData.getInviteShareInfo(requestTag)
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: InviteShareInfoEvent) {
                bindShareContent(event.content)
            }
        })
    }

    private fun bindShareContent(content: String) {
        share_wechat_friend?.setViewTag(content)
        share_wechat_timeline?.setViewTag(content)
        share_qq?.setViewTag(content)
        share_momo?.setViewTag(content)
        share_kuaishou?.setViewTag(content)
        share_tiktok?.setViewTag(content)
    }

    private fun initBind() {
        share_wechat_friend?.setOnClickListener {
            val content = it.getViewTag<String>() ?: UserData.getInstance().uid
            context?.let { context ->
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_WECHAT)) {
                    logForInviteShare("wechat")
                }
                ShareController.getInstance().shareWeChat(context, content, false)
                dismiss()
            }
        }
        share_wechat_timeline?.setOnClickListener {
            val content = it.getViewTag<String>() ?: ""
            context?.let { context ->
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_WECHAT)) {
                    logForInviteShare("wechat_moments")
                }
                ShareController.getInstance().shareWeChat(context, content, true)
                dismiss()
            }
        }
        share_qq?.setOnClickListener {
            val content = it.getViewTag<String>() ?: ""
            context?.let { context ->
                copyAndToast(content)
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_QQ)) {
                    logForInviteShare("qq")
                }
                logForInviteShare("qq")
                ShareHelper.shareQQ(context, content)
                dismiss()

            }
        }
        share_momo?.setOnClickListener {
            val content = it.getViewTag<String>() ?: ""
            context?.let { context ->
                copyAndToast(content)
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_MOMO)) {
                    logForInviteShare("momo")
                }
                ShareHelper.launchMoMo(context)
                dismiss()
            }
        }
        share_kuaishou?.setOnClickListener {
            val content = it.getViewTag<String>() ?: ""
            context?.let {
                copyAndToast(content)
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_KUAISHOU)) {
                    logForInviteShare("kuaishou")
                }
                logForInviteShare("kuaishou")
                ShareHelper.launchKuaishou(it)
                dismiss()
            }
        }
        share_tiktok?.setOnClickListener {
            val content = it.getViewTag<String>() ?: ""
            context?.let {
                copyAndToast(content)
                if (CheckUtil.checkAppIsExist(AppContext.getContext(), ShareHelper.PKG_TIKTOK)) {
                    logForInviteShare("douyin")
                }
                logForInviteShare("douyin")
                ShareHelper.launchTiktok(it)
                dismiss()
            }
        }
    }

    private fun copyAndToast(content: String) {
        ClipboardUtils.clipboardText(content)
        GlobalUI.getInstance().showToast(R.string.invite_share_copy_success_toast)
    }

    private fun initView() {
        hideWhenNotCapableOfShare(ShareHelper.PKG_MOMO, share_momo, 6)
        hideWhenNotCapableOfShare(ShareHelper.PKG_KUAISHOU, share_kuaishou, 7)
        hideWhenNotCapableOfShare(ShareHelper.PKG_TIKTOK, share_tiktok, 8)
    }

    private fun hideWhenNotCapableOfShare(pkgName: String, view: View?, failOrder: Int) {
        if (AppUtil.isAppInstalled(AppContext.getContext(), pkgName)) return
        view?.visibility = View.INVISIBLE
        view?.isEnabled = false
        view?.isClickable = false
        val layoutParams = view?.layoutParams as? FlexboxLayout.LayoutParams
        layoutParams?.order = failOrder
        view?.layoutParams = layoutParams
    }

    private fun logForInviteShare(source: String) {
        val params = Bundle()
        params.putString("from", source)
        UTUtil.getInstance().logEvent("share_invitation_code", params)
        UTUtil.getInstance().flushLogEvent()
    }
}